import { defineStore } from 'pinia'
import { accountLogin, accountLogout } from '@/service/login/login'
import type { IAccount } from '@/views/Login/types'
import { myLocalStorage } from '@/utils/storage'
import router from '@/router'
import { MessagePlugin } from 'tdesign-vue-next'

interface ILoginState {
  loading: boolean
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    loading: false
  }),
  actions: {
    async loginAction(account: IAccount) {
      this.loading = true
      const loginResult = await accountLogin(account)

      if (loginResult?.token) {
        myLocalStorage.setStorage('token', loginResult.token)
        MessagePlugin.success('登录成功')
        router.push('/main')
      }
      this.loading = false
    },

    async logoutAction() {
      try {
        const res = await accountLogout()
        myLocalStorage.deleteStorage('token')
        router.push('/login')
        MessagePlugin.success(res.message)
      } catch (error) {
        console.log(error)
      }
    }
  }
})

export default useLoginStore
